package com.zzzyh.blogbyspring.controller;

import com.zzzyh.blogbyspring.pojo.BlogInfo;
import com.zzzyh.blogbyspring.service.BlogService;
import com.zzzyh.blogbyspring.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/blog")
public class Blog {

    @Autowired
    private BlogService blogService;

    @RequestMapping("/getlist")
    public List<BlogInfo> getBlogList(){
        return blogService.getBlogList();
    }

    @RequestMapping("/getBlogDetail")
    public BlogInfo getBlogDetail(Integer id,HttpServletRequest request){
        BlogInfo blog = blogService.getBlogInfoById(id);
        String token = request.getHeader("user_token");
        Claims claims = JwtUtils.postToken(token);
        Integer uid = (Integer) claims.get("id");
        blog.setIsLoginUser(uid == blog.getUserId());
        return blog;
    }

    @RequestMapping("/addBlog")
    public Boolean addBlog(@RequestBody BlogInfo blogInfo, HttpServletRequest request){
        String token = request.getHeader("user_token");
        Claims claims = JwtUtils.postToken(token);
        if(claims == null)
            return false;
        blogInfo.setUserId((Integer) claims.get("id"));
        return blogService.addBlogInfo(blogInfo);
    }

    @RequestMapping("/deleteBlog")
    public Boolean deleteBlog(Integer id){
        return blogService.deleteBlogInfo(id);
    }

    @RequestMapping("/updateBlog")
    public Boolean updateBlog(@RequestBody BlogInfo blogInfo){
        BlogInfo blogInfoById = blogService.getBlogInfoById(blogInfo.getId());
        blogInfoById.setTitle(blogInfo.getTitle());
        blogInfoById.setContent(blogInfo.getContent());
        blogInfoById.setCreateTime(new Date());
        return blogService.updateBlogInfo(blogInfoById);
    }
}
